package com.coc.core.security.handler;
import com.alibaba.fastjson.JSON;

import com.coc.core.utils.JudgeResUtil;
import com.coc.core.redis.RedisOptCacheUtils;
import com.coc.core.jwt.JwtTokenUtil;
import com.coc.core.utils.AccessAddressUtil;
import com.coc.entity.core.JsonResult;
import com.coc.entity.core.ResConfig;
import com.coc.entity.core.ResultTool;
import com.coc.entity.system.SysUser;
import com.coc.service.system.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: songju
 * @Description: 登录成功处理逻辑
 * @Date Create in 2019/9/3
 */
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    RedisOptCacheUtils redisUtils;
    @Autowired
    private ResConfig resConfig;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        Long  expirationSeconds = resConfig.getExpirationSeconds();
        //获取请求的ip地址
        String ip = AccessAddressUtil.getIpAddress(httpServletRequest);
        Map<String,Object> map = new HashMap<>();
        map.put("ip",ip);
        //@Todo更新用户表上次登录时间、更新人、更新时间等字段,这里建议弄张关联表,数据多了,频繁操作该表可能引起事务问题,从而把表给锁了
        User userDetails = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //获取登录用户信息
        String jwtToken = JwtTokenUtil.generateToken(userDetails.getUsername(), expirationSeconds, map);
        SysUser sysUser = sysUserService.selectByName(userDetails.getUsername());
        //保存token到redis中;
        //判断是手机还是PC端

        boolean b = JudgeResUtil.JudgeIsMoblie(httpServletRequest);
        if (b){//手机端
            redisUtils.setToken("mobile_"+userDetails.getUsername(),jwtToken);
        }else {
            redisUtils.setToken("computer_"+userDetails.getUsername(),jwtToken);
        }

        sysUser.setToken("Bearer "+jwtToken);
        sysUser.setPassword("居然想看密码,不给你看~_~!!!");
        //返回json数据
        JsonResult result = ResultTool.success();
        result.setData(sysUser);
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }


}
